/**
 * 
 */
package org.statewalker.core;

import org.statewalker.core.ConditionalCallback.BarrierEvent;

/**
 * @author kotelnikov
 */
public abstract class ForkState extends AsyncState {

    @Override
    protected final void doActivate(IEvent event, ICallback callback)
        throws Exception {
        IProcessContext[] contexts = splitContext(event);
        String processName = getProcessName(event);
        String resultEventKey = getResultEventKey(event, contexts);
        BarrierEvent barrier = new BarrierEvent(resultEventKey, contexts.length);
        int len = contexts != null ? contexts.length : 0;
        if (len > 0) {
            ConditionalCallback processCallback = new ConditionalCallback(
                barrier,
                callback);
            Core core = fProcessContext.getCore();
            for (IProcessContext c : contexts) {
                core.startProcess(processName, c, processCallback);
            }
        } else {
            callback.finish(barrier);
        }
    }

    protected abstract String getProcessName(IEvent event);

    protected String getResultEventKey(
        IEvent event,
        IProcessContext[] newContexts) {
        return "ok";
    }

    protected abstract IProcessContext[] splitContext(IEvent event)
        throws Exception;
}
